package com.zhu.storesmanager.network;

import com.zhu.storesmanager.R;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.SyncModel.ResultStatus;
import com.zhu.storesmanager.models.UserData;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.SalesData;
import com.zhu.storesmanager.views.SyncView;

import android.content.Context;
import android.database.Cursor;
import android.os.Handler;

/**
 * 登录数据同步
 */
public class RemindSyncData {

	public static final int SYNC_FAILEDEND = 0;
	public static final int SYNC_SUCCESSEND = 1;

	//同步步骤
	private static final int SETUP_STARTSYNC = 1; //开始同步
	private static final int SETUP_GETMODELS = 2; //获取所有型号数据
	private static final int SETUP_GETDICTS = 3; //获取数据词典
	private static final int SETUP_GETPROJECTS = 4; //获取数据标签项目
	private static final int SETUP_GETREMINDS = 5; //获取提醒数据
	private static final int SETUP_FINISHSYNC= 6; //上报同步结束

	private Context mContext; //上下文
	private Handler mHandler = null; //消息处理Handler
	private int mConnectStep = -1; //当前同步到第几阶段
	private int retryCount = 0; //重试次数
	private boolean isFirstSync = false;

	//同步结果数据
	private SyncModel.StartResult mStartResult = null; //开始同步
	private SyncModel.ProductResult mProductResult = null;//型号数据
	private SyncModel.DictResult mDictResult = null; //数据词典数据
	private SyncModel.ProjectResult mProjectResult = null; //拜访项目标签
	private SyncModel.ReminderResult mReminderResult = null; //提醒数据

	/**
	 * 构造函数
	 * @param context 上下文
	 * @param handler 消息处理Handler
	 */
	public RemindSyncData(Context context, Handler handler){
		mContext = context;
		mHandler = handler;
	}

	/**
	 * 开始同步
	 */
	public void startSync(){
		mConnectStep = -1;
		retryCount = 0;
		resetData();
		isFirstSync = isFirstSync();
		requstStartSync();
	}

	 /**
     * 重试连接
     */
    private void retryConnect(){
    	switch(mConnectStep){
    		case SETUP_STARTSYNC:
    			requstStartSync();
    			break;
    		case SETUP_GETMODELS:
    			requstModels();
    			break;
    		case SETUP_GETDICTS:
    		    requstDicts();
    		    break;
    		case SETUP_GETPROJECTS:
    		    requstProjects();
    		    break;
    		case SETUP_GETREMINDS:
    		    requstReminds();
            case SETUP_FINISHSYNC:
            	putSyncFinish();
            	break;
    	}
    }

    /**
     * 请求同步开始
     */
    private void requstStartSync(){
    	mConnectStep = SETUP_STARTSYNC;
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	mStartResult = ParseNetworkData.parseStartSyncResult(result);
            	if(mStartResult != null && mStartResult.Status == SyncModel.SUCCEED){
            		retryCount = 0;
            		if(isFirstSync){ //第一次请求所有同步数据
            			requstModels();
            		}else{ //只请求提醒数据
            			requstReminds();
            		}
            	}else{
            	    doRequestError(mStartResult);
            	}
            }
         }
        ).callPost(HttpUtil.getSyncStartUrl(), HttpUtil.getPutSyncstartContent(DataUtils.mUserData.mUuid, isFirstSync));
    }

    /**
     * 请求型号列表数据
     */
    private void requstModels(){
    	mConnectStep = SETUP_GETMODELS;
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	mProductResult = ParseNetworkData.parseModelsResult(result);
            	if(mProductResult != null && mStartResult.Status == SyncModel.SUCCEED){
            		retryCount = 0;
            		if(DataUtils.mUserData.mRoleType == UserData.USERTYPE_SUPERVISOR){
            			requstDicts();
            		}else{
            			requstProjects();
            		}
            	}else{
            	    doRequestError(mProductResult);
            	}
            }
         }
        ).callPost(HttpUtil.getModelsUrl(), HttpUtil.getPutModelsContent(DataUtils.mUserData.mUuid));
    }

    /**
     * 请求数据词典
     */
    private void requstDicts(){
        mConnectStep = SETUP_GETDICTS;
        new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
                mDictResult = ParseNetworkData.parseDictsResult(result);
                if(mDictResult != null && mDictResult.Status == SyncModel.SUCCEED){
                    retryCount = 0;
                    requstProjects();
                }else{
                    doRequestError(mDictResult);
                }
            }
         }
        ).callPost(HttpUtil.getDictsUrl(), HttpUtil.getPutDictsContent(DataUtils.mUserData.mUuid));
    }

    /**
     * 请求数据标签项目数据
     */
    private void requstProjects(){
        mConnectStep = SETUP_GETPROJECTS;
        new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
                mProjectResult = ParseNetworkData.parseProjectResult(result);
                if(mProjectResult != null && mProjectResult.Status == SyncModel.SUCCEED){
                    retryCount = 0;
                    requstReminds();
                }else{
                    doRequestError(mProjectResult);
                }
            }
         }
        ).callPost(HttpUtil.getProjectLabelUrl(), HttpUtil.getPutProjectsContent(DataUtils.mUserData.mUuid));
    }

    /**
     * 请求提醒数据
     */
    private void requstReminds(){
        mConnectStep = SETUP_GETREMINDS;
        new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
                mReminderResult = ParseNetworkData.parseRemindResult(result);
                if(mReminderResult != null && mReminderResult.Status == SyncModel.SUCCEED){
                    retryCount = 0;
                    putSyncFinish();
                }else{
                    doRequestError(mReminderResult);
                }
            }
         }
        ).callPost(HttpUtil.getRemindUrl(), HttpUtil.getPutRemindsContent(DataUtils.mUserData.mUuid));
    }
    /**
     * 同步完成
     */
    private void putSyncFinish(){
    	int type = isFirstSync ? SyncModel.TYPE_SYNC_ALL : SyncModel.TYPE_SYNC_REMIND;
    	mConnectStep = SETUP_FINISHSYNC;
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	SyncModel.ResultStatus parseresult = ParseNetworkData.parseFinishSyncResult(result);
            	if(parseresult != null && parseresult.Status == SyncModel.SUCCEED){
            		retryCount = 0;
            		syncSuccessEnd();
            	}else{
            	    doRequestError(parseresult);
            	}
            }
         }
        ).callPost(HttpUtil.getFinishSyncUrl(), HttpUtil.getPutFinishSyncContent(DataUtils.mUserData.mUuid, mStartResult.SyncTime, type));
    }

    /**
     * 同步失败
     * @param status 状态
     * @param msg 失败消息
     */
    private void syncFail(int status, String msg){
        Log.e("syncFail="+mConnectStep);
    	if(retryCount < 3){
    		retryCount++;
    		retryConnect();
    	}else{
    		retryCount = 0;
    		mConnectStep = -1;
    		mHandler.sendEmptyMessage(SYNC_FAILEDEND);
    	}
    }

    /**
     * 同步完成
     */
    private void syncSuccessEnd(){
    	saveSyncData();
    	mConnectStep = -1;
    	retryCount = 0;
    	mHandler.sendEmptyMessage(SYNC_SUCCESSEND);
    	Log.e("syncSuccessEnd");
    }

    /**
     * 保存同步成功之后的数据
     */
    private void saveSyncData(){
    	if(mProductResult != null){
    		SyncUtil.saveModelList(mContext, mProductResult, isFirstSync);
    	}
    	if(mDictResult != null){
    		SyncUtil.saveDictsList(mContext, mDictResult, isFirstSync);
    	}
    	if(mProjectResult != null){
    		SyncUtil.saveProjectsList(mContext, mProjectResult, isFirstSync);
    	}
    	SyncUtil.saveRemindList(mContext, mReminderResult, isFirstSync);
    }

	/**
	 * 重置数据
	 */
	private void resetData(){
		mStartResult = null;
		mProductResult = null;
		mDictResult = null;
	}
	
	/**
	 * 数据清理
	 */
	public void detory(){

	}

	/**
	 * 检测是否第一次同步
	 */
	private boolean isFirstSync(){
		boolean isFirst = true;
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION,
				SyncUtil.PROJECTION, null, null, null); //查询
		if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()){ //数据存在 则表示非第一次同步
			isFirst = false;
		}
		if(cursor != null){
			cursor.close();
			cursor = null;
		}
		return isFirst;
	}

	/**
	 * 处理请求错误消息
	 */
	private void doRequestError(ResultStatus resultStatus){
	    String msg = null;
        int statusfail = 0;
        if(resultStatus == null){ //网络出现错误
            statusfail = SyncModel.FAIL_NETWORK; 
            msg = mContext.getString(R.string.network_fail);
        }else{ //数据出错
            statusfail = resultStatus.Status;
            msg = resultStatus.Msg;
        }
        syncFail(statusfail, msg);
	}
}
